package com.william.springsecurity.filter;

import com.william.springsecurity.common.Payload;
import com.william.springsecurity.config.RsaKeyProperties;
import com.william.springsecurity.pojo.SysUser;
import com.william.springsecurity.service.UserService;
import com.william.springsecurity.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RsaKeyProperties rsaKeyProperties;

    @Autowired
    private UserService userService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    // 非登录请求，请求header需要带Authorization  value为jwtToken
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwtToken = request.getHeader(jwtUtils.getHeader());
        // 白名单可跳过 完成自动登录
        if(StringUtils.isBlank(jwtToken)){
            chain.doFilter(request,response);
            return;
        }
        Jws<Claims> claimsJws = jwtUtils.parserToken(jwtToken, rsaKeyProperties.getPublicKey());
        if(Objects.isNull(claimsJws)){
            throw new JwtException("Token 异常");
        }
        Claims claims = claimsJws.getBody();
        boolean tokenExpired = jwtUtils.isTokenExpired(claims);
        if(tokenExpired){
            throw new JwtException("Token 已过期");
        }
        Payload<SysUser> infoFromToken = jwtUtils.getInfoFromToken(jwtToken, rsaKeyProperties.getPublicKey(), SysUser.class);
        SysUser sysUser = infoFromToken.getUserInfo();
        String authorities = userService.getUserAuthority(sysUser.getId());
        // 设置用户，角色权限信息
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(sysUser,sysUser.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(authorities));
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        chain.doFilter(request,response);
    }
}
